﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Inherits="Pages_Operators_ProviderItem" Codebehind="ProviderItem.aspx.cs" %>

<%@ Register Src="../Operators/Ascx/ProviderContactPopup.ascx" TagName="ProviderContactPopup"
    TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="using" runat="Server">

    <script type="text/javascript" src="/Pages/Operators/Js/provider.js"></script>

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="header" runat="Server">
    <uc1:ProviderContactPopup ID="providerContactPopup" runat="server" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="content" runat="Server">
    <table cellspacing="10" class="popup">
        <tr>
            <td rowspan="8">
                <div class="tabs">
                    <ul class="tabNavigation">
                        <li><a href="#providerinfo"><span>Provider Info</span></a></li>
                        <li><a href="#providercontact"><span>Contact Info</span></a></li>
                        <li><a href="#serviceprovider"><span>Serivce - Providers</span></a></li>
                    </ul>
                    <!-- tab containers -->
                    <div id="providerinfo">
                        <table>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Provider #:</div>
                                        <div class="field">
                                            <asp:HiddenField ID="hidProviderID" runat="server" />
                                            <asp:TextBox ID="txtProviderNumberInput" runat="server"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtProviderNumberInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Provider Name:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtProviderNameInput" runat="server"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtProviderNameInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Address line 1:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtAddressLine1Input" Width="350px" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Address line 2:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtAddressLine2Input" Width="350px" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr style="display: none">
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Country:</div>
                                        <div class="field">
                                            <asp:DropDownList ID="ddlCountryInput" runat="server" AppendDataBoundItems="true">
                                                <asp:ListItem class="firstItem" Text="Choose a country ... " Value=""></asp:ListItem>
                                            </asp:DropDownList>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
                                                InitialValue="" ControlToValidate="ddlCountryInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr style="display: none">
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            ZipCode:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtPostalCodeInput" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr style="display: none">
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            City:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtCityInput" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Email:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtEmailInput" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Website:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtWebsiteInput" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Phone:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtPhoneInput" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Fax:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtFaxNumberInput" runat="server"></asp:TextBox></div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Description:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtDescriptionInput" Width="350px" runat="server" TextMode="MultiLine"
                                                Rows="3"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtDescriptionInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr style="display: none">
                                <td>
                                    <div class="item" style="display: none">
                                        <div class="label">
                                            Active:</div>
                                        <div class="field">
                                            <asp:CheckBox ID="chkActiveInput" CssClass="checkbox" runat="server"></asp:CheckBox></div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div id="providercontact">
                        <div id="divProviderContact">
                            No contacts in this provider.
                        </div>
                    </div>
                    <div id="serviceprovider">
                        <div id="divServiceProvider">
                            No services in this provider.
                        </div>
                    </div>
                </div>
                <div class="item">
                    <span id="litNotice">
                        <asp:Literal ID="litNotice" runat="server" />
                    </span>
                </div>
                <div id="button">
                    <a id="btnSave" href="javascript:void(0)">Save</a> <a href="/Pages/Operators/ProviderList.aspx"
                        id="btnClose">Close</a>
                </div>
            </td>
        </tr>
    </table>

    <script type="text/javascript">
        // Variables
        var pageSize = 20;

        var providerIDInputCtl = $("#<%=hidProviderID.ClientID %>"),
        providerNumberInputCtl = $("#<%=txtProviderNumberInput.ClientID %>"),
        providerNameInputCtl = $("#<%=txtProviderNameInput.ClientID %>"),
        descriptionInputCtl = $("#<%=txtDescriptionInput.ClientID %>"),
        addressLine1InputCtl = $("#<%=txtAddressLine1Input.ClientID %>"),
        addressLine2InputCtl = $("#<%=txtAddressLine2Input.ClientID %>"),
        countryInputCtl = $("#<%=ddlCountryInput.ClientID %>"),
        postalCodeInputCtl = $("#<%=txtPostalCodeInput.ClientID %>"),
        cityInputCtl = $("#<%=txtCityInput.ClientID %>"),
        emailInputCtl = $("#<%=txtEmailInput.ClientID %>"),
        websiteInputCtl = $("#<%=txtWebsiteInput.ClientID %>"),
        phoneInputCtl = $("#<%=txtPhoneInput.ClientID %>"),
        faxNumberCtl = $("#<%=txtFaxNumberInput.ClientID %>");

        function clear() {
            providerIDInputCtl.val("");
            providerNumberInputCtl.val("");
            providerNameInputCtl.val("");
            descriptionInputCtl.val("");
            addressLine1InputCtl.val("");
            addressLine2InputCtl.val("");
            countryInputCtl.val(260);
            postalCodeInputCtl.val("84");
            cityInputCtl.val("HCM");
            emailInputCtl.val("");
            websiteInputCtl.val("");
            phoneInputCtl.val("");
            faxNumberCtl.val("");

            providerIDInputCtl.focus();
        }

        function insert(provider) {
            var result = false;
            defaultParameters = "{ providerEntity:" + JSON.stringify(provider) + "}";
            $.ajax({
                type: "POST",
                url: "/Update.asmx/InsertProvider",
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: (function Success(data, status) {
                    if (data.d) {
                        $("#litNotice").text("INSERT SUCCESSFUL.");
                        $("#litNotice").show(1);
                        $("#litNotice").hide(39);
                        result = true;
                    }
                    else
                        $("#litNotice").text("INSERT FAILS.");
                }),
                error: (function Error(XMLHttpRequest, status, error) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert('Insert provider failed. Detail: ' + err.Message);
                })
            });

            return result;
        }

        function update(provider) {
            var result = false;
            defaultParameters = "{ providerEntity:" + JSON.stringify(provider) + "}";
            $.ajax({
                type: "POST",
                url: "/Update.asmx/UpdateProvider",
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: (function Success(data, status) {
                    if (data.d) {
                        $("#litNotice").text("UPDATE SUCCESSFUL.");
                        result = true;
                    }
                    else {
                        $("#litNotice").text("UPDATE FAILS.");
                    }
                }),
                error: (function Error(XMLHttpRequest, status, error) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert('Update provider failed. Detail: ' + err.Message);
                })
            });
            return result;
        }

        function loadContact(contacts, pageNumber) {
            $('#divProviderContact').setTemplateURL("/Pages/Operators/template/providerContactTemplate.htm");
            $('#divProviderContact').processTemplate({ List: contacts });

            // setPageNumber
            $("gridProviderContact.pagenumber").click(function() {
                $("gridProviderContact.pagenumber").removeClass("actived");
                $(this).addClass("actived");

                var pageIndex = $(this).val();
                if (pageIndex != -1)
                    loadContact(contacts, pageIndex);
            });

            $("#gridProviderContact a.btnNew").button().click(function() {
                clearContactForm();

                $("#providerContact-dialog").dialog("open");
            });

            setEvents();
        }

        function setEvents() {
            // Button Edit
            $("#gridProviderContact a.btnEdit.new").click(function() {
                var index = $("#gridProviderContact > tbody > tr").index($(this).closest('tr'));

                editContact(index);

                $("#providerContact-dialog").dialog("open");
            });

            $("#gridServiceProvider a.btnEdit").removeClass('new');

            $("#gridProviderContact a.btnDelete.new").click(function() {

                var result = confirm("Are you sure you want to delete this record?");
                if (result) {
                    var aTag = $(this);

                    $('#gridProvider > tbody > tr').removeClass('selected');
                    aTag.parents("tr:first").css('display', 'none');
                    aTag.parents("tr:first").children("td:eq(12)").text("deleted");
                }
            });

            $("#gridProviderContact a.btnDelete").removeClass('new');
        }

        function loadService(services, pageNumber) {
            $('#divServiceProvider').setTemplateURL("/Pages/Operators/template/providerServiceTemplate.htm");
            $('#divServiceProvider').processTemplate({ "List": services, "PageNumber": pageNumber, "PageSize": pageSize, "TotalRecords": services.length });

            // setPageNumber
            $("gridServiceProvider.pagenumber").click(function() {
                $("gridServiceProvider.pagenumber").removeClass("actived");
                $(this).addClass("actived");

                var pageIndex = $(this).val();
                if (pageIndex != -1)
                    loadService(services, pageIndex);
            });
        }

        $(document).ready(function() {

            var providerID = '<%=ProviderID %>';

            if (providerID != '') {
                // load provider
                $.ajax({
                    type: "POST",
                    url: "/Get.asmx/GetProvider",
                    data: "{ providerID:'" + providerID + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: (function Success(data, status) {
                        var provider = data.d;
                        providerNumberInputCtl.attr('disabled', true);
                        providerIDInputCtl.val(provider.ProviderID);
                        providerNumberInputCtl.val(provider.ProviderNumber);
                        providerNameInputCtl.val(provider.ProviderName);
                        descriptionInputCtl.val(provider.Description);
                        addressLine1InputCtl.val(provider.AddressLine1);
                        addressLine2InputCtl.val(provider.AddressLine2);
                        countryInputCtl.val(provider.CountryID);
                        postalCodeInputCtl.val(provider.PostalCode);
                        cityInputCtl.val(provider.City);
                        emailInputCtl.val(provider.Email);
                        websiteInputCtl.val(provider.Website);
                        phoneInputCtl.val(provider.Phone);
                        faxNumberCtl.val(provider.Fax);

                        // Select provider
                        $('#gridProvider > tbody > tr').removeClass('selected');

                        loadContact(provider.ProviderContactCollection, 1);
                        loadService(provider.ServiceProviderCollection, 1);
                    }),
                    error: (function Error(XMLHttpRequest, status, error) {
                        var err = eval("(" + XMLHttpRequest.responseText + ")");
                        $("#provider").html(err.Message).fadeIn(1000);
                    })
                });
            }
            else {
                providerNumberInputCtl.removeAttr('disabled');
                clear();

                loadContact([], 1);
                loadService([], 1);
            }

            var validControl = $([]).add(providerNumberInputCtl)
                                .add(providerNameInputCtl);

            function validation() {
                var isValid = true;
                var first = true;
                validControl.each(function() {
                    isValid &= $(this).valid();
                    if (!isValid && first) {
                        $(this).focus();
                        first = false;
                    }
                });

                if (providerIDInputCtl.val() != '' && checkProvider(providerNumberInputCtl.val())) {
                    $("#litNotice").text("This Provider Number is exists.");
                    return false;
                }

                if (!isValid) return false;

                return true;
            }

            function getProvider() {
                var provider = {};

                if (providerIDInputCtl.val() != "")
                    provider.ProviderID = providerIDInputCtl.val();
                provider.ProviderNumber = providerNumberInputCtl.val();
                provider.ProviderName = providerNameInputCtl.val();
                provider.Description = descriptionInputCtl.val();
                provider.AddressLine1 = addressLine1InputCtl.val();
                provider.AddressLine2 = addressLine2InputCtl.val();
                provider.CountryID = countryInputCtl.val();
                provider.PostalCode = postalCodeInputCtl.val();
                provider.City = cityInputCtl.val();
                provider.Email = emailInputCtl.val();
                provider.Website = websiteInputCtl.val();
                provider.Phone = phoneInputCtl.val();
                provider.FaxNumber = faxNumberCtl.val();

                getContacts(provider);

                return provider;
            }

            function getContacts(provider) {
                provider.ProviderContactCollection = [];
                $("table#gridProviderContact tbody tr").each(function() {
                    var contact = {};
                    if ($(this).children("td:eq(1)").text() == '')
                        contact.IsNew = true;
                    else
                        contact.ContactID = $(this).children("td:eq(1)").text();

                    contact.Gender = $(this).children("td:eq(2)").text() == 'true';
                    contact.ContactName = $(this).children("td:eq(4)").text();
                    contact.Phone = $(this).children("td:eq(5)").text();
                    contact.WorkExtension = $(this).children("td:eq(6)").text();
                    contact.CellPhone = $(this).children("td:eq(7)").text();
                    contact.Email = $(this).children("td:eq(8)").text();
                    contact.IsDeleted = ($(this).children("td:eq(11)").text() == 'deleted');

                    provider.ProviderContactCollection.push({ "Contact": contact, "JobTitle": $(this).children("td:eq(9)").text(), "Department": $(this).children("td:eq(10)").text() });
                });
            }

            $("#btnSave").button().click(function() {

                if (!validation()) return;

                var provider = getProvider();

                if (providerIDInputCtl.val() == "") {
                    if (insert(provider)) clear(); window.location.href = "/Pages/Operators/ProviderList.aspx";
                }
                else {
                    if (update(provider)) window.location.href = "/Pages/Operators/ProviderList.aspx";
                }
            });

            $("#btnClose").button();

        });
    </script>

</asp:Content>
